
#import "OASelectDepartmentController.h"
#import "OAAttachmentsModel.h"
#import "HttpTools.h"
#import "GDataDefines.h"
#import "OADepartmentModel.h"
#import "OASelectPersonController.h"
#import "MBProgressHUD.h"
#import "OASubNameListModel.h"
#import "OANameListModel.h"
#import "OASelectPersonSecondController.h"
#import "Toast+UIView.h"
#import "FSChengbanController.h"
#import "OAExpendViewController.h"
#import "CountyDepartmentListModel.h"

@interface OASelectDepartmentController ()


@property(nonatomic,strong)NSMutableArray * personArray;

@property(nonatomic,strong)NSMutableArray * contentsArray;
@property(nonatomic,strong)NSMutableArray * groupArray; //group


@property(nonatomic,strong)NSMutableArray * rowArray;
@property(nonatomic,copy)NSString * setpString;
@property(nonatomic,copy)    NSString * info ;
@end

@implementation OASelectDepartmentController



-(NSMutableArray*)personArray{
    if (_personArray ==nil) {
        _personArray = [NSMutableArray array];
    }
    return _personArray;
}

-(NSMutableArray*)groupArray{
    
    if (_groupArray == nil) {
        _groupArray = [NSMutableArray array];
    }
    return _groupArray;
}

- (NSMutableArray*)contentsArray{
    if (_contentsArray == nil) {
        _contentsArray = [NSMutableArray array];
    }

    return _contentsArray;
}


-(NSMutableArray*)rowArray{
    if (_rowArray == nil) {
        _rowArray = [NSMutableArray array];
    }
    return _rowArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"下一环节";
            _operationItem.enabled = YES;

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
}


-(void)setupRightItems{
    _operationItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(operationACtion)];
    self.navigationItem.rightBarButtonItem = _operationItem;

}

#pragma mark 确定提交
-(void)operationACtion{
if ([_type isEqualToString:@"true"]) {
     [self loadInfoData:_string]; //点击选择的 departmanet 获得相应的数据

}else{
 
             [self loadIndoData2:_string];
}
_operationItem.enabled = NO;
   
}

-(NSMutableArray*)dataWith:(NSString*)dataString
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arrData = [[NSMutableArray alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *users = [rootElement children];
    for (int i = 0;i<[users count];i++) {
        GDataXMLElement *ele = [users objectAtIndex:i];
        if ([[ele name] isEqualToString:@"环节"]){
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [[ele attributeForName:@"流向"] stringValue];
            [arrData addObject:model];
        }
    }
    return arrData;
}


-(NSString *)returnString
{
    NSString *string = [[NSString alloc]init];
    string = @"&lt;名称&gt;%@&lt;/名称&gt;\n"
    "&lt;内容&gt;%@&lt;/内容&gt;\n";
    
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<self.attachmentArray.count; i++) {
        OAAttachmentsModel * attachModel = self.attachmentArray[i];
        [str appendString: [NSString stringWithFormat:string,attachModel.attachmentsTitle,attachModel.attachmentsURL]];
    }
    
    return str;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.departments.count;
}


#pragma mark UITbableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellIdentifier = @"cellIdentifier";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell ==nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    OADepartmentModel * model = self.departments[indexPath.row];
    cell.textLabel.text = model.department;
    if (model.isSelected) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * string = self.subItems[indexPath.row];
    for (int index = 0; index < self.departments.count; index++) {
        OADepartmentModel * model = self.departments[index];
        
        if (index == indexPath.row && [model.department isEqualToString:@"送承办"] == NO) {
        _type = @"true";
            model.isSelected = YES;
//            [self loadInfoData:string]; //点击选择的 departmanet 获得相应的数据
            _string = string;
                    [self setupRightItems];
            
        }else if (index == indexPath.row && [model.department isEqualToString:@"送承办"]){
        _type = @"false";
            model.isSelected = YES;
//            [self loadInfoData:string]; //点击选择的 departmanet 获得相应的数据
            _string = string;
                    [self setupRightItems];
            
        }
        else{
            
            model.isSelected = NO;
            
        }
    }
    
    [self.tableView reloadData];
}
//点击送承办一栏调用的方法
- (void)loadIndoData2:(NSString *)string{
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userId":userId}];
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    [HttpTools requestWithURL:KExchTree arrays:array method:KLocalTree success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        NSLog(@"%@",JSON);
        self.info = @"14";
        self.setpString = @"承办";
        NSArray * data = JSON[@"data"];
        if (data.count) {
            NSDictionary * ditc = [data firstObject];
            [self.contentsArray addObjectsFromArray:[CountyDepartmentListModel dataWithArray:ditc[@"PartNode"]]];
            
            self.groupArray = [self groups];

            NSMutableArray * subArray = [NSMutableArray array];

            for (CountyDepartmentListModel * model in self.contentsArray) {
                
                [subArray addObject:model];
            
            }
            
            self.personArray = subArray;
//            [self setupRightItems];

            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
            [self push];

    
}

-(NSMutableArray*)groups{
    NSMutableArray * tempArray = [NSMutableArray array];
    for (CountyDepartmentListModel * listModel in self.contentsArray) {
        if (listModel.bmmc.length !=0) {
            [tempArray addObject:listModel];
        }

    }
    return tempArray;
}


#pragma mark 点击选择的 departmanet 获得相应的数据
-(void)loadInfoData:(NSString*)string{
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = nil;
    if (self.fileId !=nil) {
        array = @[@{@"unid":self.fileId},@{@"userId":userId},@{@"segment":string},@{@"famxml":self.body}];
    }else if (self.detailPatchModel != nil){
        
        if ([string isEqualToString:@"<结束>"]) {
            NSString *str = [NSString stringWithFormat:@"%@",string];
            NSString *stra = [str stringByReplacingOccurrencesOfString:@"<" withString:@""];
            NSString *strb = [stra stringByReplacingOccurrencesOfString:@">" withString:@""];
            string = strb;
        }
        
        array = @[@{@"unid":self.detailPatchModel.fileId},@{@"userId":userId},@{@"segment":string},@{@"famxml":self.body}];
    }
  
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetRetStaffList success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        [self getListWithJson:JSON];
//        [self setupRightItems];
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
    
}

-(void)getListWithJson:(id)json{
    [self.groupArray removeAllObjects];
    [self.rowArray removeAllObjects];
    [self.personArray removeAllObjects];
    
    
    NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *infoArray= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoArray count];i++)
    {
        GDataXMLElement *infoElement = [infoArray objectAtIndex:i];
        self.info = [infoElement stringValue];
    }
    
    NSArray *setpArray= [rootElement elementsForName:@"环节"];
    for (int i = 0;i<[setpArray count];i++)
    {
        GDataXMLElement *setpElement = [setpArray objectAtIndex:i];
//传到确定里面
        self.setpString = [setpElement stringValue];
    }
    
    
    if ([self.info isEqualToString:@"13"]) {
        NSArray *users = [rootElement elementsForName:@"成员"];
        for (int i = 0;i<[users count];i++) {
            GDataXMLElement *ele = [users objectAtIndex:i];
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [ele stringValue];
            
//成员名字
            [self.personArray addObject: model];
        
        }

    }else if ([self.info isEqualToString:@"14"]){
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userId":userId}];
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    [HttpTools requestWithURL:KExchTree arrays:array method:KLocalTree success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        NSLog(@"%@",JSON);
        self.info = @"14";
        self.setpString = @"承办";
        NSArray * data = JSON[@"data"];
        if (data.count) {
            NSDictionary * ditc = [data firstObject];
            [self.contentsArray addObjectsFromArray:[CountyDepartmentListModel dataWithArray:ditc[@"PartNode"]]];
            
            self.groupArray = [self groups];

            NSMutableArray * subArray = [NSMutableArray array];

            for (CountyDepartmentListModel * model in self.contentsArray) {
                
                [subArray addObject:model];
            
            }
            
            self.personArray = subArray;
//            [self setupRightItems];

            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
    
}
//
//        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
//        //获取根节点
//        GDataXMLElement *rootElement = [doc rootElement];
//        OANameListModel * titleModel = [[OANameListModel alloc]init];
//        NSArray *ParentNodeData= [rootElement elementsForName:@"ParentNode"];
//        for (int i = 0;i<[ParentNodeData count];i++)
//        {
//            GDataXMLElement *ParentElement = [ParentNodeData objectAtIndex:i];
//            NSArray *ParentData= [ParentElement elementsForName:@"Parent"];
//            for (int j = 0; j<[ParentData count]; j++)
//            {
//                GDataXMLElement *element = [ParentData objectAtIndex:j];
//                titleModel.uid = [[element attributeForName:@"uid"] stringValue];
//                titleModel.value = [[element attributeForName:@"value"]stringValue];
//            }
//        }
//        
//        NSArray *PartNodeData= [rootElement elementsForName:@"PartNode"];
//        for (int i = 0;i<[PartNodeData count];i++)
//        {
//            GDataXMLElement *PNodeElement = [PartNodeData objectAtIndex:i];
//            NSArray *PNodeData= [PNodeElement elementsForName:@"PNode"];
//            for (int j = 0; j<[PNodeData count]; j++)
//            {
//                OANameListModel * subjectModel = [[OANameListModel alloc]init];
//                GDataXMLElement *element = [PNodeData objectAtIndex:j];
//                subjectModel.uid = [[element attributeForName:@"uid"] stringValue];
//                subjectModel.value = [[element attributeForName:@"value"]stringValue];
//                subjectModel.subArray  = [NSMutableArray array];
//                [self.groupArray addObject:subjectModel];
//            }
//        }
//        
//        NSArray *PersonNodeData= [rootElement elementsForName:@"PersonNode"];
//        for (int i = 0;i<[PersonNodeData count];i++)
//        {
//            GDataXMLElement *PersonElement = [PersonNodeData objectAtIndex:i];
//            NSArray *PersonData= [PersonElement elementsForName:@"Person"];
//            for (int j = 0; j<[PersonData count]; j++)
//            {
//                OASubNameListModel * subModel = [[OASubNameListModel alloc]init];
//                GDataXMLElement *element = [PersonData objectAtIndex:j];
//                subModel.pid = [[element attributeForName:@"pid"] stringValue];
//                subModel.value = [[element attributeForName:@"value"]stringValue];
//                [self.rowArray addObject:subModel];
//            }
//        }
//        
//        for (OANameListModel * nameLisModel in self.groupArray) {
//            for (OASubNameListModel * subModel in self.rowArray) {
//                if ([nameLisModel.uid isEqualToString:subModel.pid]) {
//                    [nameLisModel.subArray addObject:subModel];
//                }
//            }
//        }
//    
//        
//    }
        [self push];

}
- (void)push{

 if ( [self.info isEqualToString:@"11"]) {
     
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
        [self.view makeToast:@"提交成功"];
    }
    else if ( [self.info isEqualToString:@"15"]) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
        [self.view makeToast:@"归档成功"];
    }
    else if ( [self.setpString isEqualToString:@"承办"]) {
//送承办
        FSChengbanController *fs = [[FSChengbanController alloc] init];
        fs.personArray = self.personArray;
        fs.body = self.body;
        
        NSLog(@"%@",self.setpString);
        
        fs.setpString = self.setpString;
        if (self.fileId ) {
            fs.fileId = self.fileId;
        }else if (self.detailPatchModel){
            fs.fileId = self.detailPatchModel.fileId;
        }

        fs.contentsArray = self.contentsArray;
        fs.groupArray = self.groupArray;
        
        [self.navigationController pushViewController:fs animated:YES];
        
    }
    
    
    else if ( [self.info isEqualToString:@"14"]) {
//送承办
        FSChengbanController *fs = [[FSChengbanController alloc] init];
        fs.personArray = self.personArray;
        fs.body = self.body;
        
        NSLog(@"%@",self.setpString);
        
        fs.setpString = self.setpString;
        if (self.fileId ) {
            fs.fileId = self.fileId;
        }else if (self.detailPatchModel){
            fs.fileId = self.detailPatchModel.fileId;
        }

        fs.contentsArray = self.contentsArray;
        fs.groupArray = self.groupArray;
        
        [self.navigationController pushViewController:fs animated:YES];
        
    }
    else{
    
        for (int index = 0; index < self.departments.count; index++) {
            OADepartmentModel * model = self.departments[index];
            if (model.isSelected) {
                if (self.personArray.count >0) {
                    OASelectPersonController * selectPersonVC = [[OASelectPersonController alloc]init];
                    selectPersonVC.personArray = self.personArray;
                    selectPersonVC.body = self.body;
                    //环节
                    selectPersonVC.setpString = self.setpString;
                    if (self.fileId ) {
                        selectPersonVC.fileId = self.fileId;
                    }else if (self.detailPatchModel){
                        selectPersonVC.fileId = self.detailPatchModel.fileId;
                    }
                    
                    [self.navigationController pushViewController:selectPersonVC animated:YES];
                }else{
                    OASelectPersonSecondController * selectPersonVC = [[OASelectPersonSecondController alloc]init];
                    selectPersonVC.personArray = self.personArray;
                    selectPersonVC.body = self.body;
                    selectPersonVC.setpString = self.setpString;
                    if (self.fileId ) {
                        selectPersonVC.fileId = self.fileId;
                    }else if (self.detailPatchModel){
                        selectPersonVC.fileId = self.detailPatchModel.fileId;
                    }
                    selectPersonVC.groupArray = self.groupArray;
                    selectPersonVC.rowArray = self.rowArray;
                    [self.navigationController pushViewController:selectPersonVC animated:YES];
                }
                
                break;
            }
        }

    
    }
    
}
@end
